package com.hanhanxiaochong.zhongxiangchuanmei.view.my.act;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.JsonBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.LoginInfoBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.UserInfoPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GifSizeFilter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GlideImgManager;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.MyGlideEngine;
import com.hanhanxiaochong.zhongxiangchuanmei.util.province.GetJsonDataUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IUserInfoView;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils.FileProviderUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONArray;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/4/17.
 * Desc   : 修改个人资料act
 */

public class UpdateUserInfoActivity extends BaseActivity<UserInfoPresenter> implements IUserInfoView {

    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.view_bottomline)
    View viewBottomline;
    @BindView(R.id.img_userhead)
    ImageView imgUserhead;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.cb_female)
    CheckBox cbFemale;
    @BindView(R.id.cb_male)
    CheckBox cbMale;
    @BindView(R.id.txt_age)
    TextView txtAge;
    @BindView(R.id.txt_area)
    TextView txtArea;
    @BindView(R.id.et_user_sign)
    EditText etUserSign;
    @BindView(R.id.cb_secret)
    CheckBox cbSecret;
    private String token;

    private static final int REQUEST_CODE_CHOOSE = 0x01;

    //头像url
    private String avatarUrl;
    //昵称
    private String nickname;
    //性别0保密,1男,2女
    private String sex;
    //年龄1:20-25;2:25~30;3:30~35;4:35~40;5:40~45;6:45~50;
    private String age;
    //个性签名
    private String signature;
    private ParseDataHandler mHandler;
    //省市区
    private String province;
    private String city;
    private String district;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private List<String> ages;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_update_userinfo);
        mHandler = new ParseDataHandler(this);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void initPresenter() {
        mPresenter = new UserInfoPresenter(this);
        LoginInfoBean loginInfo = SharedPreferencesUtil.getsInstances(this).getLoginInfo();
        token = loginInfo.getToken();
    }

    @Override
    protected void init() {
        cbFemale.setOnClickListener(v -> {
            sex = "2";
            cbMale.setChecked(false);
            cbSecret.setChecked(false);
            cbFemale.setChecked(true);
        });
        cbMale.setOnClickListener(v -> {
            sex = "1";
            cbFemale.setChecked(false);
            cbSecret.setChecked(false);
            cbMale.setChecked(true);
        });
        cbSecret.setOnClickListener(v -> {
            sex = "0";
            cbFemale.setChecked(false);
            cbMale.setChecked(false);
            cbSecret.setChecked(true);
        });
        setUserInfo();
        setTopView();

        ages = new ArrayList<>();
        ages.add("20~25岁");
        ages.add("25~30岁");
        ages.add("30~35岁");
        ages.add("35~40岁");
        ages.add("40~45岁");
        ages.add("45~50岁");
    }

    /**
     * 设置本地保存用户信息
     */
    private void setUserInfo() {
        LoginInfoBean loginInfo = SharedPreferencesUtil.getsInstances(this).getLoginInfo();
        if (loginInfo == null) return;
        avatarUrl = loginInfo.getAvatar();
        GlideImgManager.glideLoader(this, avatarUrl, R.mipmap.img_error, R.mipmap.img_error, imgUserhead, 0);
        nickname = loginInfo.getUser_nicename();
        etUsername.setText(nickname);
        sex = loginInfo.getSex();
        switch (sex) {
            case "1":
                cbMale.setChecked(true);
                break;
            case "2":
                cbFemale.setChecked(true);
                break;
            case "0":
                cbSecret.setChecked(true);
                break;
        }
        age = loginInfo.getAge();
        if (age != null) {
            switch (age) {
                case "1":
                    txtAge.setText("20~25岁");
                    break;
                case "2":
                    txtAge.setText("25~30岁");
                    break;
                case "3":
                    txtAge.setText("30~35岁");
                    break;
                case "4":
                    txtAge.setText("35~40岁");
                    break;
                case "5":
                    txtAge.setText("40~45岁");
                    break;
                case "6":
                    txtAge.setText("45~50岁");
                    break;
                default:
                    break;
            }
        } else {
            txtAge.setText("");
        }
        LoginInfoBean.AddressBean address = loginInfo.getAddress();
        txtArea.setText(address != null ? address.getProvince() + address.getCity() + address.getArea() : "");
        signature = loginInfo.getSignature();
        etUserSign.setText(signature != null ? signature : "");
    }

    private void setTopView() {
        txtTitle.setText("个人资料");
        imgLeft.setImageResource(R.mipmap.icon_left);
        txtRight.setText("保存");
    }

    @OnClick({R.id.ll_leftview, R.id.ll_rightview, R.id.ll_update_userhead, R.id.ll_update_age, R
            .id.ll_update_area})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_leftview:
                finish();
                break;
            case R.id.ll_rightview:
                String nickname = etUsername.getText().toString().trim();
                if (nickname.equals("")) {
                    ToastUtils.showToast("昵称不能为空");
                } else {
                    mPresenter.updateUserInfo(token, avatarUrl, nickname, sex, age, province, city, district, etUserSign.getText().toString().trim());
                }
                break;
            case R.id.ll_update_userhead:
                Matisse.from(this)
                        .choose(MimeType.allOf())
                        .countable(true)
                        .maxSelectable(1)
                        .captureStrategy(new CaptureStrategy(true, FileProviderUtils.getFileProviderName(this)))
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new MyGlideEngine())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.ll_update_age:
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
                    txtAge.setText(ages.get(options1));
                    age = String.valueOf(options1);
                })
                        .setLineSpacingMultiplier((float) 2.0)
                        .setTitleText("年龄选择")
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(16)
                        .build();
                pvOptions.setPicker(ages);
                pvOptions.show();
                break;
            case R.id.ll_update_area:
                ShowPickerView();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> uris = Matisse.obtainResult(data);
            String filePath = FileProviderUtils.getRealPathFromURI(this, uris.get(0));
            mPresenter.uploadAvatar(token, filePath);
        }
    }

    @Override
    public void updateSuccess() {
        ToastUtils.showToast("更新成功");
        EventBus.getDefault().post(new MessageEvent("update_user_info"));
        finish();
    }

    @Override
    public void uploadAvatarSuccess(String data) {
        ToastUtils.showToast("上传成功");
        avatarUrl = RetrofitSource.image_url + data;
        GlideImgManager.glideLoader(this, avatarUrl, R.mipmap.img_error, R.mipmap.img_error, imgUserhead, 0);
    }

    private static class ParseDataHandler extends Handler {
        private Thread thread;
        private final WeakReference<UpdateUserInfoActivity> mActivity;

        private ParseDataHandler(UpdateUserInfoActivity activity) {
            this.mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        // 写子线程中的操作,解析省市区数据
                        thread = new Thread(mActivity.get()::initJsonData);
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    Log.i(mActivity.getClass().getSimpleName(), "城市数据解析成功");
                    break;
                case MSG_LOAD_FAILED:
                    Log.i(mActivity.getClass().getSimpleName(), "城市数据解析失败");
                    break;

            }
        }
    }

    private void ShowPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            province = options1Items.get(options1).getName();
            city = options2Items.get(options1).get(options2);
            district = options3Items.get(options1).get(options2).get(options3);
            txtArea.setText(province + city + district);
        })
                .setLineSpacingMultiplier((float) 2.0)
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(16)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /*
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /*
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
//                    for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
//                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
//                        City_AreaList.add(AreaName);//添加该城市所有地区数据
//                    }
                    //该城市对应地区所有数据
                    //添加该城市所有地区数据
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /*
             * 添加城市数据
             */
            options2Items.add(CityList);

            /*
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
